package common.mq.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class HttpUtil {

	public static HttpMethod getMethod(String host, Integer port, String uri,
			boolean isGet, Map<String, String> params) throws HttpException, IOException {
		HttpClient client = new HttpClient();
		client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,
				"UTF-8");
		client.getHostConfiguration().setHost(host, port == null ? 80 : port,
				"http");
		HttpMethod method = isGet ? getGetMethod(uri, params) : getPostMethod(
				uri, params); // 使用 POST 方式提交数据
		client.executeMethod(method);
		System.out.println(method.getStatusLine()); // 打印结果页面
		return method;
	}

	private static NameValuePair[] buildParam(Map<String, String> params){
		NameValuePair[] nameValuePair = null;
		if (params != null) {
			nameValuePair = new NameValuePair[params.size()];
			Set<Map.Entry<String, String>> set = params.entrySet();
			int i = 0;
			for (Map.Entry<String, String> entry : set) {
				nameValuePair[i] = new NameValuePair(entry.getKey(),
						entry.getValue());
			}
		}
		return nameValuePair;
	}
	
	private static HttpMethod getGetMethod(String uri,
			Map<String, String> params) {
//		uri += "?";
//		if(params != null){
//			StringBuffer param = new StringBuffer();
//			Set<Map.Entry<String, String>> set = params.entrySet();
//			int size = set.size();
//			int i = 0;
//			for (Map.Entry<String, String> entry : set) {
//				param.append(entry.getKey() + "=" + entry.getValue());
//				if(i < size - 1){
//					param.append("&");
//				}
//			}
//			try {
//				uri += URLEncoder.encode(param.toString(), "UTF-8");
//			} catch (UnsupportedEncodingException e) {
//				e.printStackTrace();
//			}
//		}
		GetMethod get= new GetMethod(uri);
		get.setQueryString(buildParam(params));
		return get;
	}

	private static HttpMethod getPostMethod(String uri,
			Map<String, String> params) {
		PostMethod post = new PostMethod(uri);
//		if (params != null) {
//			NameValuePair[] nameValuePair = new NameValuePair[params.size()];
//			Set<Map.Entry<String, String>> set = params.entrySet();
//			int i = 0;
//			for (Map.Entry<String, String> entry : set) {
//				nameValuePair[i] = new NameValuePair(entry.getKey(),
//						entry.getValue());
//			}
//		}
		post.setRequestBody(buildParam(params));
		return post;
	}

	public static void Close(HttpMethod method) {
		method.releaseConnection();
	}
}
